﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SimpleCompiler;
namespace SampleUI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string souceCode = TextBoxSource.Text;
            await SaveSourceFile(souceCode);            

            Parser parser = new Parser(souceCode);
            ParseResult parseResult = parser.Parse();
            RuntimeVariableScope scope = new RuntimeVariableScope(parseResult.dicParsedFunctions);
            parseResult.statement.Execute(scope);
            var topVariables = scope.TopVariables();
            var list = topVariables.ToList();
            list.Sort((item1, item2) => item1.Key.CompareTo(item2.Key));
            string result = String.Join("\n", list.Select(item => $"{item.Key} : {item.Value}"));
            TextBoxResult.Text = result;
        }

        private readonly string fileName = "source.txt";

        private async Task<string> LoadSourceFile()
        {
            try
            {
                using (var sr = new StreamReader(fileName))
                {
                    return await sr.ReadToEndAsync();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private async Task SaveSourceFile(string sourceContent)
        {
            try
            {
                using (var sr = new StreamWriter(fileName))
                {
                    await sr.WriteAsync(sourceContent);
                }
            }
            catch (Exception)
            {
                
            }
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string s = await LoadSourceFile();
            TextBoxSource.Text = s;
        }
    }
}
